﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Web.Mvc;

namespace WebApplicationFileSys.Models
{
    public class TokenHandler
    {
        public string Name { set; get; }
        public string LV { set; get; }
        public bool? Roles { set; get; }

        public TokenHandler()
        {
            if (string.IsNullOrEmpty(LoginMode.Token))
            {
                return;
            }
            if (!IsValidToken(LoginMode.Token))
            {
                return;
            }
        }
        public bool IsValidToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            SecurityToken validatedToken;
            try
            {
                // 验证JWT的有效性
                tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
            }
            catch (Exception)
            {
                return false;
            }

            var jwt = tokenHandler.ReadJwtToken(token);
            var tokenName = jwt.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Name && claim.Value.Equals(LoginMode.username));
            if (tokenName != null && validatedToken.ValidTo >= DateTime.UtcNow)
            {

                try
                {
                    Name = tokenName.Value;
                    Roles = jwt.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Role).Value.Equals("admin");
                    LV = jwt.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Name && !claim.Value.Equals(LoginMode.username))?.Value;

                }
                catch (Exception)
                {


                }


                return true;
            }
            else
            {
                return false;
            }
        }

        private TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,

                ValidIssuer = KeyValueConfig.issuer,
                ValidAudience = KeyValueConfig.audience,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(KeyValueConfig.TokeKey))
            };
        }
    }
}